

$(function () {
  let top = {
    //总数
    count: 0,
    //类型，1是文字类型，2图片类型
    type: 1,
    //页码数
    page: 1,
    //每页数量                     
    limit: 10,
  }

  let src = ''

  let index = 0

  render()

  //页面渲染
  function render() {
    $.ajax({
      method: `GET`,
      url: `/ydd_link/list?type=${top.type}&page=${top.page}&limit=${top.limit}`,
      //type类型，1是文字类型，2图片类型,  //page页码数  //每页数量limit


      headers: {},
      success: function (res) {
        // console.log(res)
        //总数
        top.count = res.data.count
        const {
          data: { data },
        } = res
        if (top.type == 1) {
          //1是文字类型
          first(data)
        } else if (top.type == 2) {
          //2图片类型
          second(data)
        }
      },
    })
  }


  //首页渲染
  function first(data) {

    let index = 0


    // let data1 = decodeURI(data)


    let arr = data
      .map((item) => {
        index++
        const { des, title, url, id } = item
        return ` <tr>
          <td>${index}</td>
          <td>${title || ''}</td>
          <td>${des || ''}</td>
          <td><span style='color:#409eff;border-radius:5px;color:#40b6ff;display:inline-block;width:60px;heigth:40px;background-color:#ecf5ff;padding-left:5px ;padding-top:3px'>文字类型</span></td>
          <td>${url || ''}</td>
          <td class='last'><button style='width: 30px;
          height: 30px ' type="button" class="layui-btn layui-btn-normal btn edit" data-id='${id}' ><i class="layui-icon" >&#xe642;</i> </button>
          <button type="button" class="layui-btn layui-btn-danger btn del" data-id='${id}'><i class="layui-icon del"  data-id='${id}'>&#xe640;</i> </button>
          </td>
        </tr>`
      })

      .join(``)


    $(`tbody`).html(arr)

    ye()
  }

  let image = ''

  //编辑

  $(`tbody`).on(`click`, '.edit', function () {

    $.ajax({
      method: 'get',
      url: `/ydd_link/rowInfo`,
      headers: {},
      data: {
        id: this.dataset.id,

      },

      success: function (res) {

        // console.log(res)
        const { data } = res
        index = layer.open({
          type: 1,
          area: ['500px'],
          title: '修改友情链接',
          content: $(`#edittxt`).html(), //这里content是一个普通的String
        })

        image = data.img
        if (data.type == 1) {

          document.querySelector(`#title`).style.display = 'block'
        } else if (data.type == 2) {
          document.querySelector(`#pic`).style.display = 'block'
          document.querySelector(
            `#img1`
          ).src = `http://124.223.14.236:8060/${image}`

        }
        render()

        form.val('editform', data)

        // console.log(res)
      },
    })
  })

  //添加按钮
  $(`.add`).on('click', function () {

    index = layer.open({
      type: 1,
      area: ['500px'],
      title: '添加友情链接',
      content: $(`#addtxt`).html(), //这里content是一个普通的String
    })
    form.render()
  })

  $('body').on(`change`, '[type=file]', function (e) {
    e.preventDefault()
    let fd = new FormData()
    console.dir(document.querySelector(`.image`))
    fd.append(`file`, document.querySelector(`.image`).files[0])
    $.ajax({
      method: 'post',
      url: `/common/upload?type=images`,
      data: fd,
      headers: {},
      contentType: false,
      processData: false,
      success: function (res) {
        document.querySelector(
          `#img1`
        ).src = `http://124.223.14.236:8060/${res.data.savePath}`
        console.log(res)
        src = res.data.savePath
      },
    })
  })
  form.on('select(test)', function (data) {
    // console.log(data.value)
    if (data.value === '1') {
      document.querySelector(`#pic`).style.display = 'none'
      document.querySelector(`#title`).style.display = 'block'
      document
        .querySelector(`[name=title]`)
        .setAttribute('lay-verify', 'required')
      document.querySelector(`[name=file]`).removeAttribute('lay-verify')
    } else if (data.value === '2') {
      document.querySelector(`#pic`).style.display = 'block'
      document.querySelector(`#title`).style.display = 'none'
      document.querySelector(`[name=title]`).removeAttribute('lay-verify')
      document
        .querySelector(`[name=file]`)
        .setAttribute('lay-verify', 'required')
    }
  })


  //取消按钮
  $(`body`).on(`click`, '.btn1', function () {
    layer.close(index)
  })

  //提交按钮
  $(`body`).on('submit', 'form', function (e) {
    e.preventDefault()
    let newarr = decodeURIComponent($(`form`).serialize(), true)
    const arr = newarr.split('&')
    const arr1 = arr
      .map((item) => item.replace(/=/, ','))
      .join(',')
      .split(',')
    const obj = {}
    for (let i = 0; i < arr1.length; i = i + 2) {
      obj[arr1[i]] = arr1[i + 1]
    }
    obj.img = src || image
    if (document.querySelector(`.btn2`)) {
      $.ajax({
        method: 'post',
        url: '/ydd_link/add',
        headers: {
          'Content-Type': 'application/json',
        },
        data: JSON.stringify(obj),
        success: function (res) {
          render()
          layer.close(index)
        },
      })
    } else if (document.querySelector(`.btn3`)) {
      console.log(obj)
      $.ajax({
        method: `post`,
        url: `/ydd_link/update`,

        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
        },
        data: JSON.stringify(obj),
        success: function (res) {
          // console.log(res)
          render()
          layer.close(index)
        },
      })
    }

    // console.log($(`form`).serialize())
  })
  $('body').on(`click`, '#up', function (e) {
    $(`[type=file]`).click()
  })

  document.querySelector(`body`).addEventListener(`click`, function (e) {
    // console.log(this)
    // console.log(e.target.classList)
    if (e.target.classList.contains(`del`)) {
      layer.confirm(
        '是否删除?',
        { icon: 3, title: '删除文章' },
        function (index) {
          //do something
          $.ajax({
            method: `get`,
            url: `/ydd_link/del`,
            headers: {
              'Content-Type': 'application/json',
            },
            data: {
              id: e.target.dataset.id,
            },
            success: function (res) {
              console.log(document.querySelectorAll(`.del`).length == 4)
              if (document.querySelectorAll(`.del`).length == 4) {
                top.page = top.page == 1 ? 1 : --top.page
              }
              // top.page--
              console.log(top.page)
              render()
              // location.reload()
            },
          })
          layer.close(index)
        }
      )
    }
  })

  element.on('tab(filter)', function (data) {
    top.type = data.index + 1
    render()
  })
  function second(data) {
    let index = 0
    // console.log(data)
    let arr = data
      .map((item) => {
        index++
        const { des, title, url, id, img } = item
        return ` <tr>
          <td>${index}</td>
          <td>
          <img src=http://124.223.14.236:8060/${img} />
          </td>
          <td>${des || ''}</td>
          <td><span style='color:#67c23a;border-radius:5px;display:inline-block;width:60px;heigth:40px;background-color:#f0f9eb;padding-left:5px ;padding-top:3px'>图片类型</span></td>
          <td>${url || ''}</td>
          <td class='last'><button type="button" class="layui-btn layui-btn-normal btn edit" data-id='${id}' ><i class="layui-icon" class='edit' >&#xe642;</i> </button>
          <button type="button" class="layui-btn layui-btn-danger btn del" data-id='${id}'><i class="layui-icon del"  data-id='${id}'>&#xe640;</i> </button>
          </td>
        </tr>`
      })
      .join(``)

    $(`tbody`).html(arr)
    ye1()
  }
  function ye1() {
    // console.log(top.count)
    var laypage = layui.laypage
    laypage.render({
      elem: 'test2', //注意，这里的 test1 是 ID，不用加 # 号
      count: top.count, //数据总数，从服务端得到
      curr: top.page,
      limit: top.limit,
      theme: '#409eff',
      limits: [2, 4, 6, 8, 10],
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        top.page = obj.curr
        top.limit = obj.limit

        //首次不执行
        if (!first) {
          //do something
          render()
        }
      },
    })
  }
  //分页
  function ye() {
    // console.log(top.count)
    var laypage = layui.laypage
    laypage.render({
      elem: 'test1', //注意，这里的 test1 是 ID，不用加 # 号
      count: top.count, //数据总数，从服务端得到
      curr: top.page,
      limit: top.limit,
      limits: [2, 4, 6, 8, 10],
      theme: '#409eff',
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        top.page = obj.curr
        top.limit = obj.limit

        //首次不执行
        if (!first) {
          //do something
          render()
        }
      },
    })
  }

  class Experience {
    constructor(container, width, height) {
      console.clear()

      this.raycaster = new THREE.Raycaster()
      this.mouse = new THREE.Vector2(0, 0)
      this._pos = {
        x: 0,
      }

      this.camera = new THREE.PerspectiveCamera(70, width / height, 1, 3000)
      this.camera.position.z = 200

      this.renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
      })
      this.renderer.setSize(width, height)
      this.renderer.setClearColor(0xffffff, 0.0)
      this.renderer.setPixelRatio(1.6)
      container.appendChild(this.renderer.domElement)

      const fps = 120
      this.fpsInterval = 1000 / fps
      this.then = Date.now()

      this.scene = new THREE.Scene()

      this.resize()
      this.bind()
      this.loop()

      this._addLights()
      this._addMeshes()
    }

    _addLights() {
      var light = new THREE.AmbientLight(0x0)
      this.scene.add(light)

      var spotLight = new THREE.SpotLight(0xf2056f, 0.68, 0)
      spotLight.position.set(150, 150, 0)
      this.scene.add(spotLight)

      var hemlight = new THREE.HemisphereLight(0xd8c7f3, 0x61dafb, 1)
      this.scene.add(hemlight)
    }

    _addMeshes() {
      var _prefix = 'https://robindelaporte.fr/codepen/play/'
      var urls = [
        _prefix + 'nx.jpg',
        _prefix + 'ny.jpg',
        _prefix + 'nz.jpg',
        _prefix + 'px.jpg',
        _prefix + 'py.jpg',
        _prefix + 'pz.jpg',
      ]

      var cubemap = THREE.ImageUtils.loadTextureCube(urls)
      cubemap.format = THREE.RGBFormat

      var geometry = new THREE.SphereGeometry(24, 32, 32)
      var material = new THREE.MeshPhysicalMaterial({
        color: 0xffffff,
        roughness: 0.3,
        metalness: 0.1,
        transparent: true,
        reflectivity: 0.56,
        envMap: cubemap,
      })

      this._sphere = new THREE.Mesh(geometry, material)
      this._sphere.position.y = -30
      this._sphere.position.x = -25
      this.scene.add(this._sphere)

      var geometryTorus = new THREE.TorusBufferGeometry(16, 8, 16, 100)
      this._torus = new THREE.Mesh(geometryTorus, material)
      this._torus.position.y = 30
      this._torus.position.x = 30
      this._torus.rotation.x = 2.3
      this._torus.rotation.y = 0.3
      this.scene.add(this._torus)

      var geometryCone = new THREE.ConeBufferGeometry(8, 16, 32)
      this._cone = new THREE.Mesh(geometryCone, material)
      this._cone.position.y = 12
      this._cone.position.x = -50
      this._cone.position.z = 3
      this._cone.rotation.x = -0.3
      this._cone.rotation.z = 0.7
      this.scene.add(this._cone)

      this._torus.material.opacity = 0
    }

    animateIn() {
      TweenMax.to(this._torus.material, 0.6, { opacity: 1 })

      TweenMax.fromTo(
        this._torus.scale,
        0.6,
        { x: 0.8, y: 0.8, z: 0.8 },
        { x: 1.35, y: 1.35, z: 1.35 }
      )
      TweenMax.fromTo(
        this._torus.position,
        0.6,
        { x: 10, y: 20 },
        { x: 30, y: 40 }
      )

      TweenMax.fromTo(
        this._torus.rotation,
        0.6,
        { x: 2.0, y: -0.3 },
        { x: 2.3, y: 0.3 }
      )

      TweenMax.fromTo(
        this._sphere.scale,
        0.6,
        { x: 0.8, y: 0.8, z: 0.8 },
        { x: 1.15, y: 1.15, z: 1.15 }
      )
      TweenMax.fromTo(
        this._sphere.position,
        0.6,
        { x: -10, y: -10 },
        { x: -30, y: -40 }
      )

      TweenMax.fromTo(
        this._cone.scale,
        0.6,
        { x: 0.8, y: 0.8, z: 0.8 },
        { x: 1.35, y: 1.35, z: 1.35 }
      )
      TweenMax.fromTo(
        this._cone.position,
        0.6,
        { x: -30, y: 2, z: 3 },
        { x: -70, y: 12, z: 3 }
      )

      TweenMax.fromTo(
        this._cone.rotation,
        0.6,
        { x: -0.2, z: 0.0 },
        { x: -0.3, z: 0.7 }
      )
    }

    animateOut() {
      TweenMax.to(this._torus.material, 0.6, { opacity: 0 })

      TweenMax.to(this._torus.scale, 0.6, { x: 0.8, y: 0.8, z: 0.8 })
      TweenMax.to(this._torus.position, 0.6, { x: 10, y: 20 })
      TweenMax.to(this._torus.rotation, 0.6, { x: 2.0, y: -0.3 })

      TweenMax.to(this._sphere.scale, 0.6, { x: 0.8, y: 0.8, z: 0.8 })
      TweenMax.to(this._sphere.position, 0.6, { x: -10, y: -10 })

      TweenMax.to(this._cone.scale, 0.6, { x: 0.8, y: 0.8, z: 0.8 })
      TweenMax.to(this._cone.position, 0.6, { x: -30, y: 2, z: 3 })
      TweenMax.to(this._cone.rotation, 0.6, { x: -0.2, z: 0.0 })
    }

    bind() {
      window.addEventListener('resize', this.resize.bind(this), false)
      document.body.addEventListener(
        'mousemove',
        this.onMouseMove.bind(this),
        false
      )

      document.querySelector('a').addEventListener('mouseenter', () => {
        TweenMax.to('.ok', 0.6, { scale: 1.35 })
        this.animateIn()
      })

      document.querySelector('a').addEventListener('mouseleave', () => {
        TweenMax.to('.ok', 0.6, { scale: 1.0 })
        this.animateOut()
      })
    }

    onMouseMove(event) {
      this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1
      this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1
    }

    loop() {
      this.raf = window.requestAnimationFrame(this.loop.bind(this))

      const now = Date.now()
      const delta = now - this.then

      if (delta > this.fpsInterval) {
        // this.scene.update()
        this.camera.position.x +=
          this.mouse.x * (window.innerWidth * 0.02) -
          this.camera.position.x * 0.03
        this.camera.position.y +=
          -(this.mouse.y * (window.innerHeight * 0.02)) -
          this.camera.position.y * 0.03
        this.camera.lookAt(this.scene.position)

        this.renderer.render(this.scene, this.camera)
        this.then = now
      }
    }

    resize() {
      //     this.innerWidth = window.innerWidth
      //     this.innerHeight = window.innerHeight
      //     this.camera.aspect = this.innerWidth / this.innerHeight
      //     this.camera.updateProjectionMatrix()
      //     this.renderer.setSize( this.innerWidth, this.innerHeight )
    }
  }

  const container = document.querySelector('.home')
  let experience = new Experience(container, 400, 300)
})



















